package com.googlecode.publicholiday;

import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

public class SimpleFileParser implements FileParser {

    private final static Logger LOG = LoggerFactory.getLogger(SimpleFileParser.class);
    private final static DateTimeFormatter DATE_FORMAT = ISODateTimeFormat.date(); // yyyy-MM-dd

    @Override
    public Map<String, SortedSet<LocalDate>> parse(File file) throws Exception {
        LOG.debug("Attempting to load Public Holidays from: {}", file);
        Map<String, SortedSet<LocalDate>> dataStore = new HashMap<String, SortedSet<LocalDate>>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line = reader.readLine();
            int count = 0;
            while (line != null) {
                count++;
                addLineToDataStore(dataStore, line);
                line = reader.readLine();
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignore) {
                }
            }
        }
        LOG.debug("Loaded {} Public Holidays");
        return dataStore;
    }

    private void addLineToDataStore(Map<String, SortedSet<LocalDate>> dataStore, String line) {
        String[] cols = line.split(",");
        if (cols.length == 2) {
            if (!dataStore.containsKey(cols[0])) {
                dataStore.put(cols[0], new TreeSet<LocalDate>());
            }
            dataStore.get(cols[0]).add(DATE_FORMAT.parseLocalDate(cols[1]));
        }
    }

}
